package cn.flyboy.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

public class FileHelper {
    /*
     * 下载压缩文件夹
     */
    public static void downloadZip(HttpServletRequest req, HttpServletResponse res, String folderPath, String name) throws IOException {
        File folder = new File(folderPath);

        //检查文件夹是否存在
        while (!folder.isDirectory()) {
            folder.mkdirs();
        }

        String rootPath = req.getSession().getServletContext().getRealPath("/files/" + name);
        System.out.println(rootPath + "++++++++++++++++");

        //创建临时文件夹用于存放压缩文件
        File temDir = new File(rootPath + "/" + UUID.randomUUID().toString().replaceAll("-", ""));
        if (!temDir.exists()) {
            temDir.mkdirs();
        }

        //生成需要下载的文件，存放在临时文件夹内
        File srcFile = folder;

        File desFile = new File(temDir.getAbsolutePath() + File.separator + srcFile.getName() + ".zip");

        FileOutputStream fos = new FileOutputStream(desFile);
        ZipUtils.toZip(srcFile.getAbsolutePath(), fos, true);

        // 设置文件下载头
        res.addHeader("Content-Disposition", "attachment;filename=answer.zip");
        // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        res.setContentType("multipart/form-data");


        ZipUtils.toZip(temDir.getAbsolutePath(), res.getOutputStream(), true);

        //删除临时文件和文件夹
        File[] listFiles = temDir.listFiles();
        for (int i = 0; i < listFiles.length; i++) {
            listFiles[i].delete();
        }
        temDir.delete();
    }

    /*
     * 删除某个路径下的文件与文件夹
     */
    public static void deleteFile(String absPath) {

        File file = new File(absPath);
        cycleDelete(file);
    }

    /*
     * 循环删除文件或文件夹
     */
    public static void cycleDelete(File file) {
        if (!file.exists()) {
            System.out.println("文件不存在!");
        }
        if (file.isFile()) {
            System.out.println("文件：" + file.getPath());
            file.delete();
            System.out.println("----删除文件：" + file.getName() + "------");
        }
        if (file.isDirectory()) {
            System.out.println("文件夹：" + file.getPath());
            File[] fs = file.listFiles();
            for (File f : fs) {
                cycleDelete(f);
            }
            if (file.delete()) {
                System.out.println("----删除文件夹：" + file.getName() + "------");
            } else {
                System.out.println("文件夹删除失败");
            }
        }
    }
}
